// pages/address/address.js
import {deleteAddress, getAddress, setDefault} from "../../service/address";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow(){
    //请求API,获取数据
    getAddress().then(res=>{
      // console.log(res)
      this.setData({
        address: res.data
      })
    })
  },
  /**
   * 跳转到添加地址
   */
  toAddAddress(){
    wx.navigateTo({
      url:'/pages/address_add/address_add'
    })
  },
  /**
   * 跳转到编辑页面
   */
  toEdit(event){
    wx.navigateTo({
      url:'/pages/address_add/address_add?id=' + event.target.id
    })
  },
  /**
   * 选择完地址之后，跳回订单预览页
   */
  selectAddress(event){
    console.log(getCurrentPages())
    const pages = getCurrentPages()
    if(pages[pages.length -2].route == 'pages/center/center') return

    const id = event.target.id
    wx.setStorageSync('select_address_id',id)
    wx.navigateBack()
  },
  /**
   * 删除
   */
  deleteAddress(event){
    const  id = event.target.id

    //弹窗确认
    wx.showModal({
      title:'提示',
      content:'确认要删除吗',
      success:(res)=> {
        if(!res.confirm) return
        //请求API，执行删除
        deleteAddress(id).then(()=>{
          //更新数据
          this.setData({
            address: this.data.address.filter(item=>item.id != id)
          })
          //弹窗提醒
          wx.showToast({
            title:'删除成功',
            icon:'success'
          })
        })
      }
    })
  },

  /**
   * 设置为默认地址
   */
  onSetDefault(event){
    const id= event.target.id

    //请求API,执行设置默认
    setDefault(id).then(()=>{
      //更新数据
      this.setData({
        address: this.data.address.map(item=>{
          if(item.id == id){
            item.is_default = 1
          }else{
            item.is_default = 0
          }
          return item
        })
      })
      //弹窗提醒
      wx.showToast({
        title:'设置成功',
        icon:'success'
      })
    })
  }
})